package com.huahang.fashionpress.aspect;

import com.huahang.fashionpress.enums.ExceptionEnum;
import com.huahang.fashionpress.exception.NotloginException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 前台登录控制模块
 * @author : 王翰聪
 * @since : 2019/08/25
 * @version : 1.0
 */
@Aspect
@Component
public class LoginControllerAspect {

    @Pointcut(value = "execution(public * com.huahang.fashionpress.controller.OrderController.*(..)) ||" +
            " execution(public * com.huahang.fashionpress.controller.AddressController.*(..)) ||"+
            "execution(public * com.huahang.fashionpress.controller.ShopcarController.*(..))")
    public void dovery() {

    }

    @Before(value = "dovery()")
    public void checkUserID(JoinPoint joinPoint) throws ServletException, IOException {
        //先从request中取得session
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        HttpSession session = attributes.getRequest().getSession();

        //从session中尝试取得userID
        Integer userID = (Integer) session.getAttribute("userID");
        //判断是否存在
        if(userID == null || userID <= 0){
            //请求转发至登录页面
            throw new NotloginException(ExceptionEnum.NOT_LOGIN_CLIENT);
//            response.sendRedirect("/fashionpress/login/");
        }
    }
}
